import argparse
import os
import numpy as np
# import math
# import itertools
import time
import datetime
import sys
# import skimage

# import torchvision.transforms as transforms
import paddle.vision.transforms as transforms
from torchvision.utils import save_image

from torch.utils.data import DataLoader
# from torchvision import datasets
from torch.autograd import Variable

# 自定义模块
from models.model import *
# from models.CasNet import *
# from models.ResNet import * 
# from models.ResNetUnet import *
# from models.Unet import *
from datasets import *
# from models.feature import *
# from models.pix2pix import *
# from models.feature import *

# import torch.nn as nn
import paddle.nn as nn
# import torch.nn.functional as F
import paddle as torch

from tensorboardX import SummaryWriter
writer = SummaryWriter()

# path = "/home/sd/lijitao/project/MedGAN/new_data/mr"
path = r"/home/aistudio/data/data118396/madic_data"
# path = "/home/sd/lijitao/project/gans/PyTorch-GAN-master/implementations/pix2pix/dataset/mr"
parser = argparse.ArgumentParser()
parser.add_argument("--epoch", type=int, default=0, help="epoch to start training from")
parser.add_argument("--n_epochs", type=int, default=10000, help="number of epochs of training")
parser.add_argument("--dataset_name", type=str, default="mr", help="name of the dataset")
parser.add_argument("--batch_size", type=int, default=1, help="size of the batches")
parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate")
parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient")
parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient")
parser.add_argument("--decay_epoch", type=int, default=100, help="epoch from which to start lr decay")
parser.add_argument("--n_cpu", type=int, default=1, help="number of cpu threads to use during batch generation")
parser.add_argument("--img_height", type=int, default=256, help="size of image height")
parser.add_argument("--img_width", type=int, default=256, help="size of image width")
parser.add_argument("--channels", type=int, default=3, help="number of image channels")
parser.add_argument(
    "--sample_interval", type=int, default=2000, help="interval between sampling of images from generators"
)
parser.add_argument("--checkpoint_interval", type=int, default=500, help="interval between model checkpoints")
opt = parser.parse_args()
# print(opt)

os.makedirs("images/%s" % opt.dataset_name, exist_ok=True)
os.makedirs("saved_models/%s" % opt.dataset_name, exist_ok=True)

# # 释放闲置内存
# if hasattr(torch.cuda, 'empty_cache'):
# 	torch.cuda.empty_cache()

cuda = True if torch.cuda.is_available() else False
# cuda = False

# os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
# os.environ['CUDA_VISIBLE_DEVICES'] = '1' 
# cuda = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

# 损失函数

criterion_GAN = torch.nn.MSELoss()
'''L1Loss: 平均绝对误差（MAE）'''
criterion_pixelwise = torch.nn.L1Loss()

# Loss weight of L1 pixel-wise loss between translated image and real image
# 翻译图像和真实图像
lambda_pixel = 100

# Calculate output of image discriminator (PatchGAN)
patch = (1, opt.img_height // 2 ** 4, opt.img_width // 2 ** 4)

# Initialize generator and discriminator
# generator = ResnetGenerator(3, 3)
# generator = UnetGenerator(3, 3, 8) # 采用这个生成器，生成的图像更有“想象力”，但很糊

# generator = UnetGenerator(3, 3, 8)
# generator = UNET()
# discriminator = Discriminator()

# generator = ResNet(Bottleneck, [3, 4, 6, 3, 3, 6, 4, 3])
# generator = CasNet()
# generator = UNET(in_channels=3, out_channels=3)

discriminator = Discriminator()
# discriminator = NLayerDiscriminator(3)
generator = GeneratorUNet()
if cuda:
    generator = generator.cuda()
    discriminator = discriminator.cuda()
    criterion_GAN.cuda()
    criterion_pixelwise.cuda()

if opt.epoch != 0:
    # 加载已经训练好的模型
    generator.load_state_dict(torch.load("saved_models/%s/generator_%d.pth" % (opt.dataset_name, opt.epoch)))
    discriminator.load_state_dict(torch.load("saved_models/%s/discriminator_%d.pth" % (opt.dataset_name, opt.epoch)))
else:
    # 初始化权重
    generator.apply(weights_init_normal)
    discriminator.apply(weights_init_normal)

# 优化器
optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))
optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))

# 设置数据加载器
transforms_ = [
    transforms.Resize((opt.img_height, opt.img_width), Image.BICUBIC),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]

dataloader = DataLoader(
    ImageDataset(path, transforms_=transforms_),
    batch_size=opt.batch_size,
    shuffle=True,
    num_workers=opt.n_cpu,
)

val_dataloader = DataLoader(
    ImageDataset(path, transforms_=transforms_, mode="val"),
    batch_size=10,
    shuffle=True,
    num_workers=1,
)

# Tensor type
Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor

def cal_psnr(im1, im2):
    mse = (np.abs(im1 - im2) ** 2).mean()
    psnr = 10 * np.log10(255 * 255 / mse)
    return psnr


def eval(im1, im2):
    im1 = im1.cpu().detach().numpy()
    im2 = im2.cpu().detach().numpy()
    mse = (np.abs(im1 - im2) ** 2).mean()
    psnr = 10 * np.log(255 * 255 / mse)
    # im1 和 im2 都为灰度图像，uint8 类型
    # print(im1.shape, im2.shape)
    # ssim = skimage.measure.compare_ssim(im1, im2, data_range=255, multichannel=True)
    return mse, psnr    #   , ssim
    # 

def sample_images(batches_done):
    """Saves a generated sample from the validation set"""
    imgs = next(iter(val_dataloader))
    real_A = Variable(imgs["B"].type(Tensor))
    real_B = Variable(imgs["A"].type(Tensor))
    fake_B = generator(real_A)
    # mse, psnr, ssim = eval(real_B, fake_B)
    # print(mse, psnr, ssim)

    img_sample = torch.cat((real_A.data, fake_B.data, real_B.data), -2)
    save_image(img_sample, "images/%s/%s.png" % (opt.dataset_name, batches_done), nrow=5, normalize=True)





# ----------
#  Training
# ----------

prev_time = time.time()

for epoch in range(opt.epoch, opt.n_epochs):
    for i, batch in enumerate(dataloader):

        # Model inputs
        real_A = Variable(batch["B"].type(Tensor))
        real_B = Variable(batch["A"].type(Tensor))

        # Adversarial ground truths
        valid = Variable(Tensor(np.ones((real_A.size(0), *patch))), requires_grad=False)
        fake = Variable(Tensor(np.zeros((real_A.size(0), *patch))), requires_grad=False)
        # valid = Variable(Tensor(np.ones((155, *patch))), requires_grad=False)
        # fake = Variable(Tensor(np.zeros((155, *patch))), requires_grad=False)

        # ------------------
        #  训练生成器
        # ------------------

        optimizer_G.zero_grad()

        # GAN loss
        # L1 loss

        fake_B = generator(real_A)
        

        # pred_fake = discriminator(fake_B, real_A)
        pred_fake = discriminator(fake_B, real_B)
        
        loss_GAN = criterion_GAN(pred_fake, valid)
        # Pixel-wise loss
        loss_pixel = criterion_pixelwise(fake_B, real_B)


        # 特征提取器实现风格迁移损失

        # Style Loss
        loss_style = feature_loss(fake_B, real_B)

        # Total Loss
        loss_G = loss_GAN + lambda_pixel * loss_pixel   + loss_style

        loss_G.backward()

        optimizer_G.step()

        # ---------------------
        #  训练判别器
        # ---------------------

        optimizer_D.zero_grad()

        # Real loss
        # pred_real = discriminator(real_B, real_A)
        pred_real = discriminator(fake_B.detach(), real_B)

        loss_real = criterion_GAN(pred_real, valid)

        # Fake loss
        pred_fake = discriminator(fake_B.detach(), real_A)
        # pred_fake = discriminator(fake_B.detach(), real_B)
        loss_fake = criterion_GAN(pred_fake, fake)

        # Total loss
        loss_D = 0.5 * (loss_real + loss_fake)

        loss_D.backward()
        # loss_D.backward(retain_graph=True)

        optimizer_D.step()

        # --------------
        #  Log Progress
        # --------------

        # 输出训练进度
        batches_done = epoch * len(dataloader) + i
        batches_left = opt.n_epochs * len(dataloader) - batches_done
        time_left = datetime.timedelta(seconds=batches_left * (time.time() - prev_time))
        prev_time = time.time()

        # Print log
        sys.stdout.write(
            "\r[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f, pixel: %f, adv: %f] ETA: %s"
            % (
                epoch,
                opt.n_epochs,
                i,
                len(dataloader),
                loss_D.item(),
                loss_G.item(),
                loss_pixel.item(),
                loss_GAN.item(),
                time_left,
            )
        )

        mse, psnr = eval(real_B, fake_B)        
        # TensorboardX  可视化训练过程
        writer.add_scalar('Loss_D', loss_D.item(), epoch)
        writer.add_scalar('Loss_G', loss_G.item(), epoch)
        writer.add_scalar('loss_pixel()', loss_pixel.item(), epoch)
        writer.add_scalar('loss_GAN', loss_GAN.item(), epoch)
        writer.add_scalar('mse', mse, epoch)
        writer.add_scalar('psnr', psnr, epoch)
        # writer.add_scalar('ssim', ssim, epoch)
        
        # If at sample interval save image
        if batches_done % opt.sample_interval == 0:
            sample_images(batches_done)

    if opt.checkpoint_interval != -1 and epoch % opt.checkpoint_interval == 0:
        # Save model checkpoints
        torch.save(generator.state_dict(), "saved_models/%s/generator_%d.pth" % (opt.dataset_name, epoch))
        torch.save(discriminator.state_dict(), "saved_models/%s/discriminator_%d.pth" % (opt.dataset_name, epoch))

writer.close()